/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.runtime.component
{
	import com.edi.runtime.Event.*;
	import com.edi.utils.BOPStringUtils;
	
	import flash.events.FocusEvent;
	import flash.events.MouseEvent;
	
	import mx.controls.TextInput;
	import mx.events.ValidationResultEvent;
	import mx.managers.ToolTipManager;
	import mx.styles.StyleManager;
	import mx.validators.EmailValidator;
	import mx.validators.NumberValidator;
	import mx.validators.PhoneNumberValidator;
	import mx.validators.StringValidator;
	import mx.validators.Validator;

	/**
	 * 文本录入控件
	 * 在MXML中的用法示例：<EDITextInput notNull="false"  fieldLength="500"  visible="true"  primaryKey="false"  fieldType="string"  table="meetingitem"  field="meetingname"  id="meetingNameTxt"  height="22"  x="68" y="34" width="577"></EDITextInput>
	 * @author HW
	 *
	 */


	public class EDITextInput extends TextInput implements IEDIComponent
	{
		private var _field:String;
		private var _fieldtype:String;
		private var _fieldlength:int=0;
		public var notNull:Boolean = false;
		private var _table:String;
		private var _primaryKey:String="";
		private var _displayType:String;
		private var _validatorResult:Boolean;
		private var validat:Validator;

		public var verify:RegExp;


		/**
		 * EDITextInput构造函数
		 *
		 */
		public function EDITextInput()
		{
			EDIApplication.outputDebug("EDITextInput 开始调用");

			super();
			EDIApplication.outputDebug("EDITextInput: " + text);
			//this.addEventListener(FocusEvent.FOCUS_IN,focusHandler);
			//初始化提示信息的样式
			initErrorTipsStyle();
		}
		
		private function focusHandler(event:FocusEvent):void{
			if(BOPStringUtils.trim(this.text) == "最多"+this.fieldLength.toString()+"个字符"){
				this.text = "";
			}
			this.setStyle("color","black");
			this.removeEventListener(FocusEvent.FOCUS_IN,focusHandler);
		}
		
		private function initErrorTipsStyle():void{
			StyleManager.getStyleDeclaration(".errorTip").setStyle("fontSize","12");
		}


		/**
		 * 实现IEDIComponent接口的属性
		 * @param value
		 *
		 */
		public function set table(value:String):void
		{
			_table=value;
			EDIEventProxy.listenerDataRolling(value, this);
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @return
		 *
		 */
		public function get table():String
		{
			return _table;
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @param value
		 *
		 */
		public function set primaryKey(value:String):void
		{
			_primaryKey=value;
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @return
		 *
		 */
		public function get primaryKey():String
		{
			return _primaryKey;
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @param value
		 *
		 */
		public function set field(value:String):void
		{
			_field=value;
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @return
		 *
		 */
		public function get field():String
		{
			return _field;
		}

		/**
		 * 实现IEDIComponent接口的属性，同时对录入数据的合法性进行检查
		 * @param value
		 *
		 */
		public function set fieldType(value:String):void
		{
			_fieldtype=value;
			switch (value)
			{
				case "int":
				{
					restrict="0-9";
					break;
				}
				case "float":
				{
					restrict="0-9\."
					break;
				}
				case "decimal":
				{
					restrict="0-9\."
					break;
				}
			}
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @return
		 *
		 */
		public function get fieldType():String
		{
			return _fieldtype;
		}

		/**
		 * 字段长度，同时对录入数据的合法性进行检查
		 * @param value
		 *
		 */
		public function set fieldLength(value:int):void
		{
			//this.setStyle("color","#999999");
			_fieldlength=value;
			//this.text = "最多"+value.toString()+"个字符";
			maxChars=value;
		}

		/**
		 *  字段长度，同时对录入数据的合法性进行检查
		 * @return
		 *
		 */
		public function get fieldLength():int
		{
			return _fieldlength;
		}

		/**
		 * 实现IEDIComponent接口的方法
		 * @param event
		 *
		 */
		public function dataRollingHandler(event:EDIDataEvent):void
		{
			text=event.value[field];
		}

		/**
		 * 实现IEDIComponent接口的属性
		 * @return
		 *
		 */
		public function get ediValue():String
		{
			return text;
		}

		/**
		 * 进行数据合法性检查
		 * @return
		 *
		 */
		public function check():Boolean
		{
			var ret:Boolean=false;
			if (!notNull)
			{
				if (text == "")
				{
					return ret;
				}
			}

			if (fieldLength > 0)
			{
				var length:int=text.replace(/[^\x00-\xff]/g, "xx").length;
				if (fieldLength < length)
				{
					return ret;
				}
			}

			if (verify != null)
			{
				if (!verify.test(text))
				{
					return ret;
				}
			}

			return true;
		}

		public function set displayType(value:String):void
		{
			this._displayType=value;
		}

		public function get displayType():String
		{
			return this._displayType;
		}

		/**
		 * 初始化验证提示信息
		 *
		 */
		private function initErrorInfo(disType:String):Validator
		{
			disType=BOPStringUtils.trim(disType).toLowerCase();
			if (disType == "int" || disType == "decimal")
			{
				this.validat=new NumberValidator();
				NumberValidator(validat).source=this;
				NumberValidator(validat).property="text";
				NumberValidator(validat).integerError="数字必须为整数！";
				NumberValidator(validat).invalidCharError="数字中包含非法字符！";
				NumberValidator(validat).lowerThanMinError="数字过小！";
				NumberValidator(validat).requiredFieldError="请输入字符！";
				NumberValidator(validat).decimalPointCountError="数字中出现过多小数点";
				NumberValidator(validat).negativeError="数字不能为负数.";
				NumberValidator(validat).invalidFormatCharsError="数字中包含无效格式字符.";
				NumberValidator(validat).precisionError="数字不符合精度要求.";
			}
			else if (disType == "string")
			{
				this.validat=new StringValidator();
				//字符串验证组件初始化属性
				StringValidator(validat).source=this;
				StringValidator(validat).property="text";
				
				StringValidator(validat).requiredFieldError="字符不能为空.";
				StringValidator(validat).tooLongError="字符串超过指定长度.";
			}
			else if (disType == "email")
			{
				this.validat=new EmailValidator();
				//邮件验证组件初始化属性
				EmailValidator(validat).source=this;
				EmailValidator(validat).property="text";
				EmailValidator(validat).requiredFieldError="请输入邮件地址.";
				EmailValidator(validat).invalidCharError="邮件地址中存在无效字符.";
				EmailValidator(validat).tooManyAtSignsError="邮件地址中存在过多@字符.";
				EmailValidator(validat).invalidPeriodsInDomainError="邮件地址中存在连续句点.";
				EmailValidator(validat).missingPeriodInDomainError="邮件地址中不存在用户名.";
				EmailValidator(validat).missingAtSignError="邮件地址中必须包含@符号.";
				EmailValidator(validat).missingUsernameError = "邮件地址中缺少用户名.";
			}
			else if (disType == "phone")
			{
				this.validat=new PhoneNumberValidator();
				//手机号码验证组件初始化
				PhoneNumberValidator(validat).source=this;
				PhoneNumberValidator(validat).property="text";
				PhoneNumberValidator(validat).invalidCharError="手机号码中包含无效字符.";
				PhoneNumberValidator(validat).wrongLengthError="手机号码长度至少11位.";
			}
			
			return this.validat;
		}

		/**
		 * 获得验证后的结果
		 * @return
		 * 如验证通过,则返回true;否则返回false.
		 *
		 */
		public function get validatorResult():Boolean
		{
			var valResult:Boolean=true;
			if(!this._displayType){
				this.displayType = "string";
			}
			var disTypeInner:String = BOPStringUtils.trim(this._displayType).toLowerCase();
			if(disTypeInner=="string" || disTypeInner=="int" || disTypeInner=="decimal" || disTypeInner=="email" || disTypeInner=="phone"){
				
			}else{
				this.displayType = "string";
			}
			if (!validat)
			{
				this.validat=initErrorInfo(this._displayType);
				
			}
			validat.required=notNull;
			switch (BOPStringUtils.trim(this._displayType).toLowerCase())
			{
				case "int":
				{

					restrict="0-9";
					NumberValidator(validat).domain="int";
					var vre:ValidationResultEvent=NumberValidator(validat).validate();
					if (vre.type == ValidationResultEvent.INVALID)
					{
						valResult=false;
					}
					break;
				}
				case "decimal":
				{
					restrict="0-9\."
					NumberValidator(validat).domain="real";
					var vre:ValidationResultEvent=NumberValidator(validat).validate();
					if (vre.type == ValidationResultEvent.INVALID)
					{
						valResult=false;
					}
					break;
				}
				case "string":
				{

					if (this._fieldlength)
					{
						StringValidator(validat).maxLength=_fieldlength;
					}
					var vre:ValidationResultEvent=StringValidator(validat).validate();
					if (vre.type == ValidationResultEvent.INVALID)
					{
						valResult=false;
					}
					break;
				}
				case "email":
				{
					var vre:ValidationResultEvent=EmailValidator(validat).validate();
					if (vre.type == ValidationResultEvent.INVALID)
					{
						valResult=false;
					}
					break;
				}
				case "phone":
				{
					var vre:ValidationResultEvent=PhoneNumberValidator(validat).validate();
					if (vre.type == ValidationResultEvent.INVALID)
					{
//						ToolTipManager.createToolTip(vre.message,this.,this.y,"errorTipRight");
						valResult=false;
					}
					break;
				}
				default:
				{

				}
			}
			this.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER,true));
			return valResult;
		}
		
		override public function set text(value:String):void{
			super.text = value;
			if(BOPStringUtils.trim(value) == ""){
				this.errorString = "";
			}
		}
		
	}
}